package com.notice.entity;

import cn.hutool.log.LogFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 *
 * @author DZL
 * @date 2023/1/13 18:50
 */
public class AsyncManager {

    /**
     * 线程池
     */
    private final ThreadPoolTaskExecutor executor;
    private final int waitTime = 6;

    private AsyncManager() {
        executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(2);
        executor.setCorePoolSize(2);
        executor.setQueueCapacity(2000);
        executor.setKeepAliveSeconds(100);
        executor.setThreadNamePrefix("log_notice_");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            LogFactory.get().info("钉钉通知异步线程池资源释放");
            executor.shutdown();
            try {
                if (!executor.getThreadPoolExecutor().awaitTermination(waitTime, TimeUnit.SECONDS)) {
                    executor.getThreadPoolExecutor().shutdownNow();
                }
            } catch (InterruptedException ie) {
                executor.getThreadPoolExecutor().shutdownNow();
                Thread.currentThread().interrupt();
            }
        }));
    }

    private static final AsyncManager ME = new AsyncManager();

    public static AsyncManager me() {
        return ME;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(Runnable task) {
        executor.execute(task);
    }


}
